import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:factoryside/home/page_login.dart';
import 'package:factoryside/utils/request_util.dart';
import 'package:factoryside/utils/utils.dart';
import 'package:factoryside/widget/update_dialog.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bugly/flutter_bugly.dart';
import 'package:open_file/open_file.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';


class SettingPage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return _SettingPage();
  }

}
class _SettingPage extends State<SettingPage>{

  bool isCheck_install= true;
  bool isCheck_maintain =true;
  GlobalKey<UpdateDialogState> _dialogKey = new GlobalKey();
  //int _position=0;
 String _hint="当前选中了";
 bool hasNew=false;

  String savePath;

  CancelToken cancelToken;
  @override
  void initState() {
    super.initState();
    if(Platform.isIOS){
      PackageInfo.fromPlatform().then((value) => this.setState(() {
        PackageInfo packageInfo=value;
        String appName = packageInfo.appName;
        String packageName = packageInfo.packageName;
        String version = packageInfo.version;
        String buildNumber = packageInfo.buildNumber;
        print('appName:$appName,packageName:$packageName,version:$version,buildNumber:$buildNumber');
        RequestUtil.getInstance().get('http://itunes.apple.com/lookup?id=1488412445').then((value){
          var updateInfo=json.decode(value.data);
          print(updateInfo);
          double appStoreVersion=double.parse(updateInfo['results'][0]['version']);
          if(appStoreVersion>double.parse(version)){
            setState(() {
              hasNew=true;
            });
          }
        });
      }));
    }else{
      FlutterBugly.getUpgradeInfo().then((_upgradeInfo) {
        if (_upgradeInfo!=null) {
          setState(() {
            hasNew=true;
          });
        }
      });
    }
  }
  void _showUpdateDialog(UpgradeInfo _upgradeInfo) {
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (_) => _buildDialog(_upgradeInfo),
    );
  }
  Widget _buildDialog(UpgradeInfo _upgradeInfo) {
    return WillPopScope(
        onWillPop: () async => false,
        child: UpdateDialog(
          key: _dialogKey,
          upgradeInfo: _upgradeInfo,
          onClickWhenDownload: (_msg) {
            //提示不要重复下载
            showToast(_msg);
          },
          onClickWhenNotDownload: () {
            //下载apk，完成后打开apk文件，建议使用dio+open_file插件
            downloadApk(_upgradeInfo);
          },
        ));
  }
  void downloadApk(UpgradeInfo _upgradeInfo) async {
    Directory tempDir = await getExternalStorageDirectory();
    String tempPath = tempDir.path;
    savePath = '$tempPath/update_${_upgradeInfo.versionName}.apk';
    File file=File(savePath);
    file.exists().then((value) async {
      if(value){
        _installApk();
      }else{
        Dio dio = new Dio();
        dio.options.connectTimeout = 5000; //5s
        dio.options.receiveTimeout = 3000;
        cancelToken = CancelToken();//可以用来取消操作
        await dio.download(_upgradeInfo.apkUrl, savePath,
            onReceiveProgress: (_received, _total){
              _updateProgress((_received*100)~/_total);
            },options: Options(receiveTimeout: 5*60*1000),cancelToken: cancelToken).catchError((_error){
          print(_error);
        });
      }
    });
  }

  void _installApk() async {
    Navigator.of(context).pop();
    print(savePath);
    print(Uri.file(savePath));
    OpenFile.open(savePath);
  }
  //dio可以监听下载进度，调用此方法
  void _updateProgress(_progress) {
    setState(() {
      print('下载进度$_progress%');
      if(_progress==100){
        _installApk();
      }
      if (_dialogKey.currentState!=null) {
        _dialogKey.currentState.progress = _progress;
      }else{
        cancelToken.cancel();
      }
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromARGB(255,245,242,245),
      appBar: buildAppBar('设置',null,context),
     body:

     SingleChildScrollView(
       child:Column(
         children: <Widget>[
           GestureDetector(
             child: Container(
               color: Colors.white,
               padding: EdgeInsets.symmetric(horizontal: 10),
               height: 55,
               child: Row(
                 children: [
                   Expanded(child: Text('安全设置')),
                   Image.asset(
                     'assets/right.png',
                     width: 20,
                     height: 20,
                   ),
                 ],
               ),
             ),
             onTap: () {
               showToast('待开发...');
//               Navigator.push(this.context,
//                   CupertinoPageRoute(builder: (BuildContext context) {
//                     return SafeSettingPage();
//                   }));
             },
           ),
           Divider(color: Colors.grey,height: 0.3,),
//           GestureDetector(
//             child: Container(
//               color: Colors.white,
//               padding: EdgeInsets.symmetric(horizontal: 10),
//               height: 55,
//               child: Row(
//                 children: [
//                   Expanded(child: Text('接单设置')),
//                   Image.asset(
//                     'assets/right.png',
//                     width: 20,
//                     height: 20,
//                   ),
//                 ],
//               ),
//             ),
//             onTap: () {
//               Navigator.push(this.context,
//                   CupertinoPageRoute(builder: (BuildContext context) {
//                     return OrderSettingPage();
//                   }));
//             },
//           ),
           /*清除缓存*/
//           Container(
//             width: double.infinity,
//             height: 55,
//             decoration: BoxDecoration(
//                 color: Colors.white,
//                 border: Border(top: BorderSide(color: Colors.grey,width: 0.3))
//             ),
//             child: Row(children: <Widget>[
//               Padding(padding: EdgeInsets.only(left: 10),child:Text("清除缓存")),
//               Expanded(child: Container(
//                 alignment: Alignment.centerRight,
//                 margin: EdgeInsets.only(right: 15),
//                 child:
//                 Store.connect<ConfigModel>(
//                     builder: (context, ConfigModel provider, child) {
//                       return  Image.asset(
//                               ImageHelper.wrapAssets("ic_clean${ThemeUtil.SetPhotoColor(provider.theme)}.png"),
//                                width: 25,height: 25);
//                     }
//                 ),
//
//
//               ))
//             ],
//             ),
//           ),

           /*检查更新*/
           Visibility(
//             visible: Platform.isAndroid,
             child: GestureDetector(
               child:Container(
                 width: double.infinity,
                 height: 55,
                 padding: EdgeInsets.symmetric(horizontal: 10),
                 decoration: BoxDecoration(
                     color: Colors.white,
                     border: Border(top: BorderSide(color: Colors.grey,width: 0.3))
                 ),
                 child: Row(children: <Widget>[
                   Expanded(child: Text("检查更新")),
                   Visibility(
                       visible: hasNew,
                       child: Container(
                           padding: EdgeInsets.only(right: 10),
                           child: Icon(Icons.fiber_new,color: Colors.red))),
                   Visibility(
                       visible: !hasNew,
                       child: Container(
                           padding: EdgeInsets.only(right: 10),
                           child: Text('已经是最新版'))),
                   Image.asset(
                     'assets/right.png',
                     width: 20,
                     height: 20,
                   ),
                 ],
                 ),
               ),
               onTap: (){
//                  FlutterBugly.checkUpgrade(isManual: true);
                 if(Platform.isIOS){
                   PackageInfo.fromPlatform().then((value) => this.setState(() {
                     PackageInfo packageInfo=value;
                     String appName = packageInfo.appName;
                     String packageName = packageInfo.packageName;
                     String version = packageInfo.version;
                     String buildNumber = packageInfo.buildNumber;
                     print('appName:$appName,packageName:$packageName,version:$version,buildNumber:$buildNumber');
                     RequestUtil.getInstance().get('http://itunes.apple.com/lookup?id=1488412445').then((value){
                       var updateInfo=json.decode(value.data);
                       print(updateInfo);
                       double appStoreVersion=double.parse(updateInfo['results'][0]['version']);
                       if(appStoreVersion>double.parse(version)){
                         showDialog(
                           barrierDismissible: false,
                           context: context,
                           builder: (_) => AlertDialog(
                               backgroundColor: Colors.transparent,
                               contentPadding: EdgeInsets.zero,
                               content: buildContent(updateInfo['results'][0])
                           ),
                         );
                       }else{
                         showToast('已经是最新版本');
                       }
                     });
                   }));
                 }else{
                   FlutterBugly.getUpgradeInfo().then((_upgradeInfo) {
                     if (_upgradeInfo!=null) {
                       _showUpdateDialog(_upgradeInfo);
                     }else{
                       showToast('已经是最新版本');
                     }
                   });
                 }
               },
             ),
           ),




           /*设置主题颜色*/
//           Container(
//             width: double.infinity,
//             height: 120,
//             color: Colors.white,
//             margin: EdgeInsets.only(top: 12),
//             child: Column(
//               children: <Widget>[
//                 /**/
//                 Container(
//                     alignment: Alignment.centerLeft,
//                     width: double.infinity,
//                     padding: EdgeInsets.only(left: 10),
//                     height: 40,
//                     decoration: BoxDecoration(
//                         border: Border(top: BorderSide(color: Colors.grey,width: 0.3),bottom:BorderSide(color: Colors.grey,width: 0.3))
//                     ),
//                     child:
//                     Row(children: <Widget>[
//                       Text("设置主题色",style: TextStyle(fontSize: 14)),
//                       Expanded(child: Container(
//                           alignment: Alignment.centerRight,
//                           margin: EdgeInsets.only(right: 10),
//                           child: Container(
//                             padding: EdgeInsets.only(left: 4,right: 4,top: 2,bottom: 2),
//                             decoration: BoxDecoration(
//                                 color: Color.fromARGB(200, 255,152,0),
//                                 borderRadius: BorderRadius.all(Radius.circular(4))
//                             ),
//
//                             child: Text("${_hint}${ThemeUtil.GetColorName(Store.value<ConfigModel>(context).theme)}"
//                                 ,style: TextStyle(fontSize: 12,color: Colors.white)),
//                           )
//
//                       ))
//
//                     ],)
//
//
//
//
//                 ),
//
//                 Container(
//                     width: double.infinity,
//                     height: 80,
//                     padding: EdgeInsets.only(left: 10,right: 10),
//                     decoration: BoxDecoration(
//                         border: Border(bottom: BorderSide(color: Colors.grey,width: 0.2))
//                     ),
//                     child:Row(
//                       children: <Widget>[
//                         Expanded(flex:1,child:
//                          selecttheme_item(0, "blue","默认蓝")
//                         ),
//                         Expanded(flex:1,child:
//                          selecttheme_item(1, "yellow","柠檬黄")),
//                         Expanded(flex:1,child:
//                          selecttheme_item(2, "green","薄荷绿")
//                         ),
//                         Expanded(flex:1,child:
//                          Container(
//                           child: Center(
//                             child: Container(
//                               alignment: Alignment.center,
//                               width: 58,
//                               height: 58,
//                               decoration: BoxDecoration(
//                                   color: Colors.white,
//                                   borderRadius: BorderRadius.all(Radius.circular(28)),
//                                   border: Border.all(color: Colors.black,width: 0.2)
//                               ),
//                               child:
//                               Padding(padding: EdgeInsets.all(6),
//                                 child:Text("更多主题敬请期待",style: TextStyle(fontSize: 10))
//                               ),
//                             ),
//                           )
//
//
//                         )
//
//                         ),
//                       ],
//                     )
//                 ),
//               ],
//             ),
//           ),
//           Container(
//             color: Colors.transparent,
//             width: double.infinity,
//             height: 50,
//             margin: EdgeInsets.all(10),
//             child: RaisedButton(
//               onPressed: () {
//                 SharedPreferences.getInstance().then((value) {
//                   value.clear();
//                   value.setBool("isFirst", true);
//                 });
//                 ///跳转到起始页并关闭所有页面
//                 Navigator.pushAndRemoveUntil(
//                   context,
//                     MaterialPageRoute(builder: (context) => Login()),
//                       (Route<dynamic> route) => false,
//                 );
//               },
//               child: Text(
//                 '退出登录',
//                 style: TextStyle(color: Colors.white,fontSize: 18),
//               ),
//               color: ColorsUtil.hexToColor(Api.btnColor),
//             ),
//           ),
           Container(
             margin: EdgeInsets.all(10),
             child: ElevatedButton(
                 onPressed: () {
                   SharedPreferences.getInstance().then((value) {
                     value.clear();
                     value.setBool("isFirst", true);
                   });
                   ///跳转到起始页并关闭所有页面
                   Navigator.pushAndRemoveUntil(
                     context,
                     MaterialPageRoute(builder: (context) => Login()),
                         (Route<dynamic> route) => false,
                   );
                 },
                 child: Container(
                     padding: EdgeInsets.symmetric(vertical: 15),
                     child: Row(
                       mainAxisAlignment: MainAxisAlignment.center,
                       children: [
                         Text('退出登录'),
                       ],
                     ))),
           ),
           
         ],
       ),
     )




    );
  }

  Widget buildContent(json) {
    double width=MediaQuery.of(context).size.width-48;
    double height=MediaQuery.of(context).size.height/2;
    var btnTxt='立即更新';
    print('版本v${json['version']}');
    print('大小${json['fileSizeBytes']}');
    return Container(
      height: height,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Stack(
            alignment: Alignment.bottomCenter,
            children: [
              Image.asset(
                'assets/tc_head.png',
//            width: double.infinity,
                height: width*382/792,
                fit: BoxFit.fill,
              ),
              Positioned(
                  bottom: 15,
                  child: Text(
                    '版本：v${json['version']}    大小：${getPrintSize(int.parse(json['fileSizeBytes']))}\n更新时间：${json['currentVersionReleaseDate']}',
                    style: TextStyle(color: Colors.white,fontSize: 10),
                  ))
            ],
          ),
          Expanded(
            child: Container(
              color: Colors.white,
              child: SingleChildScrollView(
                child: Container(
                  padding: EdgeInsets.all(10),
                  color: Colors.white,
                  child: Text(
                    "更新说明：\n${json['releaseNotes']}",
                    style: TextStyle(fontSize: 12),
                  ),
                ),
              ),
            ),
          ),
          Container(
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.vertical(bottom:Radius.circular(5))),
            child: Row(
              children: [
                Expanded(
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 10),
                    child: OutlinedButton(
                      child: Text(
                        '下次再说',
                        style: TextStyle(fontSize: 12),
                      ),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 10),
                    child: OutlinedButton(
                      child: Text(
                        '立即更新',
                        style: TextStyle(fontSize: 12),
                      ),
                      onPressed: () {
                        gotoAppStore();
                        Navigator.of(context).pop();
                      },
                    ),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

}